package com.hs.srm.admin.modules.material.controller;

import java.awt.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hs.srm.admin.common.util.ExcelUtil;
import com.hs.srm.admin.modules.material.entity.MaterialEntity;
import com.hs.srm.admin.modules.material.entity.MaterialLeadEntity;
import com.hs.srm.admin.modules.material.service.MaterialLeadService;
import com.hs.srm.admin.modules.material.service.MaterialService;
import com.hs.srm.base.common.config.SysConfig;
import com.hs.srm.base.common.utils.DictDataUtil;
import com.hs.srm.base.common.utils.EntityUtils;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.common.utils.DateUtils;
import com.landray.kmss.km.review.webservice.KmReviewParamterForm;
import lombok.var;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.hs.srm.admin.modules.material.entity.MaterialFactoryEntity;
import com.hs.srm.admin.modules.material.service.MaterialFactoryService;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import sunnykid.character.UtilCharacter;

import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 物料工厂数据模板
 * @Author socik
 * @Date 2019/6/17 15:33
 */
@RestController
@RequestMapping("/materialFactory")
public class MaterialFactoryController extends AbstractController {


    private static final long serialVersionUID = -4123823577744890422L;
    @Value("${oa.host}")
    private String oaHost;

    @Value("${oa.port}")
    private String oaPort;

    @Value("${oa.materialFactory-templateId}")
    private String materialFactoryTemplateId;

    /**
     * @Description: 注入业务层
     */
    @Autowired
    private MaterialFactoryService materialFactoryService;
    @Autowired
    private MaterialLeadService materialLeadService;
    @Autowired
    private MaterialService materialService;

    /**
     * @Description: 物料查询
     */
    @ResponseBody
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        // 物料库存数据

        PageUtils page = materialFactoryService.queryPage(params);
        List<MaterialFactoryEntity> list = (List<MaterialFactoryEntity>) page.getList();
        list.forEach(materialFactoryEntity -> {
            MaterialEntity materialEntity = this.materialService.selectMaterialByCode(materialFactoryEntity.getMaterialCode());
            if (materialEntity != null) {
                if (materialEntity.getRemark() != null && materialEntity.getRemark() != "") {
                    materialFactoryEntity.setRemark(materialEntity.getRemark());
                }
            }
        });
        list = EntityUtils.valToTxt(list);
        page.setList(list);
        return R.ok(page);
    }

    /**
     * @Description 物料领用
     * @Param [pkId]
     * @Return org.springframework.web.servlet.ModelAndView
     * @Author socik
     * @Date 2019/5/28 13:20
     */
    @ResponseBody
    @RequestMapping("/toLead/{materialFactoryId}/{leadMan}")
    public R toLead(@PathVariable("materialFactoryId") String pkId, @PathVariable("leadMan") String leadMan) {
        String[] result = pkId.split(",");
        //获取用户名
        for (int i = 0; i < result.length; i++) {
            SysUserEntity username = this.getUser();
            //查询所有数据
            MaterialFactoryEntity materialFactoryEntity = this.materialFactoryService.selectById(result[i]);
            //查询领料单看其中数据
            MaterialLeadEntity materialLeadEntity = this.materialLeadService.selectEntityByUser(materialFactoryEntity.getMaterialCode(), materialFactoryEntity.getWerks(), username.getUsername());
            if (materialLeadEntity != null) {
                return R.error("该物料已经添加领料单,请勿重复添加!");
            }
            MaterialLeadEntity leadEntity = new MaterialLeadEntity();
            leadEntity.setMaterialCode(materialFactoryEntity.getMaterialCode());
            leadEntity.setWerks(materialFactoryEntity.getWerks());
            leadEntity.setAccount(username.getUsername());
            leadEntity.setLeadMan(leadMan);
            this.materialLeadService.insert(leadEntity);
        }
        return R.ok();
    }

    /**
     * @Description 保存领用数据
     * @Param [materialLeadEntity]
     * @Return com.hs.srm.common.utils.R
     * @Author socik
     * @Date 2019/5/28 16:18
     */

    @ResponseBody
    @RequestMapping("/save")
    public String save(String datalist, HttpServletResponse response) {
        SysUserEntity username = this.getUser();
        //组装json数组
        JSONArray jsonArray = JSONArray.parseArray(datalist);
        String[] pkid = new String[jsonArray.size()];
        for (int i = 0; i < jsonArray.size(); i++) {
            pkid[i] = jsonArray.getJSONObject(i).getString("materialLeadId");
            MaterialLeadEntity materialLeadEntity = this.materialLeadService.selectById(jsonArray.getJSONObject(i).getString("materialLeadId"));
            MaterialFactoryEntity materialFactoryEntity = this.materialFactoryService.selectMaterialFactoryByCode(materialLeadEntity.getMaterialCode(), materialLeadEntity.getWerks());
            materialLeadEntity.setLeadnum(jsonArray.getJSONObject(i).getIntValue("leadnum"));
            materialLeadEntity.setLeadDept(jsonArray.getJSONObject(i).getString("leadDept"));
            materialLeadEntity.setReturntime(DateUtils.stringToDate(jsonArray.getJSONObject(i).getString("returntime"), DateUtils.DATE_PATTERN));
            materialLeadEntity.setAccount(username.getUsername());
            materialFactoryEntity.setUsecont(materialFactoryEntity.getUsecont() + materialLeadEntity.getLeadnum());
            materialFactoryEntity.setIsLead(materialFactoryEntity.getIsLead());
            this.materialFactoryService.updateById(materialFactoryEntity);
            this.materialLeadService.updateById(materialLeadEntity);
        }
       File file= this.export(pkid);
        try {
            File save=new File(file.getAbsolutePath());
            Desktop.getDesktop().print(save);
            Thread.sleep(10000);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ExcelUtil.delete(new File(SysConfig.getUploadPath() + File.separator));
        return "OK";
    }



    /**
     * @Description 返回前台数据展示
     * @Param [pkId]
     * @Return org.springframework.web.servlet.ModelAndView
     * @Author socik
     * @Date 2019/5/30 9:27
     */

    @RequestMapping("/toReturn/{materialFactoryId}")
    public ModelAndView toReturn(@PathVariable("materialFactoryId") String pkId) {
        //查询所有数据
        //设置数据转换文本显示前台
        var materialLeadEntity = this.materialLeadService.selectById(pkId);
        MaterialFactoryEntity materialFactoryEntity = this.materialFactoryService.selectMaterialFactoryByCode(materialLeadEntity.getMaterialCode(), materialLeadEntity.getWerks());
        ModelAndView modelAndView = new ModelAndView("modules/inforecord/material_return");
        materialFactoryEntity.setWerks(DictDataUtil.valToTxt(materialFactoryEntity.getWerks(), DictDataUtil.DictType.GC));
        materialFactoryEntity.setStorageLocation(DictDataUtil.valToTxt(materialFactoryEntity.getStorageLocation(), DictDataUtil.DictType.KCDD));
        materialLeadEntity.setLeadDept(DictDataUtil.valToTxt(materialLeadEntity.getLeadDept(), DictDataUtil.DictType.LYBM));
        materialFactoryEntity.setUsecont(materialFactoryEntity.getQunatity() - materialFactoryEntity.getUsecont());
        materialLeadEntity.setReturnNum(materialLeadEntity.getLeadnum() - materialLeadEntity.getReturnNum());
        //两个实体类 添加到前台展示数据
        modelAndView.addObject("materialLeadEntity", materialLeadEntity);
        modelAndView.addObject("materialFactoryEntity", materialFactoryEntity);
        return modelAndView;
    }

    /**
     * @Description 物料归还逻辑编写
     * @Param [materialLeadEntity]
     * @Return com.hs.srm.common.utils.R
     * @Author socik
     * @Date 2019/5/30 9:30
     */

    @ResponseBody
    @RequestMapping("/return")
    public R returnMaterial(MaterialLeadEntity materialLeadEntity) {
        if (materialLeadEntity != null) {
            int type = materialLeadEntity.getReturnType();
            Date date = DateUtils.currentDateTime();
            //查询所有工厂数据
            MaterialFactoryEntity materialFactoryEntity = this.materialFactoryService.selectMaterialFactoryByCode(materialLeadEntity.getMaterialCode(), DictDataUtil.txtToVal(materialLeadEntity.getWerks(), DictDataUtil.DictType.GC));
            MaterialLeadEntity entity = this.materialLeadService.selectById(materialLeadEntity.getMaterialLeadId());
            //判断归还数量是否大于领用数量
            if (materialLeadEntity.getReturnNum() > entity.getLeadnum() - entity.getReturnNum()) {
                return R.error("归还数量不可大于总领用数量!");
            }
            if (type == 2) {
                materialFactoryEntity.setQunatity(materialFactoryEntity.getQunatity() - materialLeadEntity.getReturnNum());
                materialFactoryEntity.setUsecont(materialFactoryEntity.getUsecont() - materialLeadEntity.getReturnNum());
            } else {
                materialFactoryEntity.setUsecont(materialFactoryEntity.getUsecont() - materialLeadEntity.getReturnNum());
            }
            materialFactoryEntity.setIsLead(materialFactoryEntity.getIsLead() + 1);
            this.materialFactoryService.updateById(materialFactoryEntity);
            materialLeadEntity.setActualtime(date);
            materialLeadEntity.setWerks(DictDataUtil.txtToVal(materialLeadEntity.getWerks(), DictDataUtil.DictType.GC));
            materialLeadEntity.setLeadDept(DictDataUtil.txtToVal(materialLeadEntity.getLeadDept(), DictDataUtil.DictType.BM));
            materialLeadEntity.setReturnNum(entity.getReturnNum() + materialLeadEntity.getReturnNum());
            this.materialLeadService.updateById(materialLeadEntity);
            return R.ok();
        }
        //查询所有数据
        return R.error();
    }


    /**
     * @Description 物料归还逻辑编写
     * @Param [materialLeadEntity]
     * @Return com.hs.srm.common.utils.R
     * @Author socik
     * @Date 2019/5/30 9:30
     */

    @ResponseBody
    @RequestMapping("/selectNum")
    public R returnMaterial() {
        SysUserEntity username = this.getUser();
        List<MaterialLeadEntity> list = this.materialLeadService.selectEntityListByUser(username.getUsername());
        return R.ok(list.size());
    }

    /**
     * @Description 跳转领料单界面
     * @Param []
     * @Return org.springframework.web.servlet.ModelAndView
     * @Author socik
     * @Date 2019/6/4 8:51
     */
    @RequestMapping("/toLeadD")
    public ModelAndView toLeadD() {
        SysUserEntity username = this.getUser();
        List<MaterialLeadEntity> list = this.materialLeadService.selectEntityListByUser(username.getUsername());
        for (MaterialLeadEntity entity : list) {
            MaterialFactoryEntity materialFactoryEntity = this.materialFactoryService.selectMaterialFactoryByCode(entity.getMaterialCode(), entity.getWerks());
            entity.setMaterialDesc(materialFactoryEntity.getMaterialDesc());
            entity.setUsecont(materialFactoryEntity.getQunatity() - materialFactoryEntity.getUsecont());
        }
        ModelAndView modelAndView = new ModelAndView("modules/inforecord/material_lead");
        modelAndView.addObject("itemList", list);
        return modelAndView;
    }

    /**
     * @Description: 导出打印领料单
     */
    public File export(String[] materialLeadId) {
        List<String> idList = Arrays.asList(materialLeadId);
        List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
        Map<String, Object> map = new HashMap<String, Object>();
        MaterialLeadEntity entity = this.materialLeadService.selectById(idList.get(0));
        MaterialEntity material = this.materialService.selectMaterialByCode(entity.getMaterialCode());
        MaterialFactoryEntity materialFactoryEntity = this.materialFactoryService.selectMaterialFactoryByCode(entity.getMaterialCode(), entity.getWerks());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String reg = "[^\u4e00-\u9fa5]";
        if (entity != null) {
            map.put("werks", entity.getWerks());
            map.put("leadMan", entity.getLeadMan());
            map.put("leadDept", (DictDataUtil.valToTxt(entity.getLeadDept(), DictDataUtil.DictType.LYBM)).replaceAll(reg, ""));
            map.put("createtime", format.format(entity.getCreatetime()));
            map.put("materialType", DictDataUtil.valToTxt(material.getMaterialType(), DictDataUtil.DictType.WULX));
            map.put("storageLocation", (DictDataUtil.valToTxt(materialFactoryEntity.getStorageLocation(), DictDataUtil.DictType.KCDD)).replaceAll(reg, ""));
        }
        for (int i = 0; i < idList.size(); i++) {
            Map<String, String> lm = new HashMap<>();
            MaterialLeadEntity materialLeadEntity = this.materialLeadService.selectById(idList.get(i));
            MaterialEntity materialEntity = this.materialService.selectMaterialByCode(materialLeadEntity.getMaterialCode());
            MaterialFactoryEntity materialFactory = this.materialFactoryService.selectMaterialFactoryByCode(materialLeadEntity.getMaterialCode(), materialLeadEntity.getWerks());

            if (materialEntity != null) {
                String dw = materialEntity.getBasicUnit();
                lm.put("index", (i + 1) + "");
                lm.put("materialCode", materialLeadEntity.getMaterialCode());
                lm.put("leadnum", materialLeadEntity.getLeadnum().toString());
                lm.put("num", "");
                lm.put("materialDesc", materialEntity.getMaterialDesc());
                lm.put("basicUnit", dw);
                lm.put("remark", materialEntity.getRemark());
                lm.put("pc", "-");
                lm.put("chuwei", materialFactory.getStorage());
                mapList.add(lm);
            }
        }
        map.put("maplist", mapList);
        String exportTemplatePath = SysConfig.getExportTemplatePath();
        TemplateExportParams params = new TemplateExportParams(
                exportTemplatePath + UtilCharacter.FILE_SEPARATOR + "领料单.xlsx", true
        );
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        String pathtem = SysConfig.getUploadPath() + File.separator;
        File savefile = new File(pathtem);
        if (!savefile.exists()) {
            savefile.mkdirs();
        }
        OutputStream os = null;
        String Path = "";
        Path = savefile.getAbsolutePath() + File.separator + "pickList.xlsx";
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(Path);
            workbook.write(fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        File file = new File(Path);
        return file;
    }

    /**
     * @Description 跳转到编辑页面
     * @Param [materialFactoryId]
     * @Return org.springframework.web.servlet.ModelAndView
     * @Author socik
     * @Date 2019/6/10 13:44
     */

    @RequestMapping("/toLeadE/{materialFactoryId}")
    public ModelAndView toLeadE(@PathVariable("materialFactoryId") String materialFactoryId) {
        ModelAndView modelAndView = new ModelAndView("modules/inforecord/material_factory_edit");
        MaterialFactoryEntity materialFactoryEntity = this.materialFactoryService.selectById(materialFactoryId);
        modelAndView.addObject("materialFactoryEntity", materialFactoryEntity);
        return modelAndView;
    }

    /**
     * @Description 更新方法
     * @Param [materialFactoryEntity]
     * @Return com.hs.srm.common.utils.R
     * @Author socik
     * @Date 2019/6/10 13:50
     */

    @ResponseBody
    @RequestMapping("/update")
    public R update(MaterialFactoryEntity materialFactoryEntity) {
        // 根据id进行更新，没有传值的属性就不会更新
        boolean flg = this.materialFactoryService.updateById(materialFactoryEntity);
        if (flg) {
            return R.ok("更新成功!");
        }
        return R.error("更新失败!");
    }

    public void sendToOv() {
        Map<String, Object> params = new HashMap<>();
        PageUtils page = materialFactoryService.queryPage(params);
        List<MaterialFactoryEntity> list = (List<MaterialFactoryEntity>) page.getList();
        this.createForm(list);
    }

    private KmReviewParamterForm createForm(List<MaterialFactoryEntity> materialFactoryEntities) {
        // 文档模板id
        KmReviewParamterForm form = new KmReviewParamterForm();
        //正式系统中的模板id：16a6c5b3754c17fb57b6b51448582ea6
        //16b1c48e217796f301080674e799a9a8
        form.setFdTemplateId(materialFactoryTemplateId);
        // 文档标题
        form.setDocSubject("库存预警明细表");
        // 流程发起人
        form.setDocCreator("{\"LoginName\":\"2183603\"}");
        // 文档关键字
        form.setFdKeyword("[\"物料\",  \"库存\"]");
        JSONObject formValues = null;
        JSONObject formValuesdetail = null;
        JSONObject finalformValuesdetail = null;
        List<Map<String, Object>> Lists = new ArrayList<Map<String, Object>>();

		/*//*模板id：16b2a5702ba9032b9836eb04e5b81934
        库存预警明细表id：fd_stock_alert
        物料号：fd_material_number
        物料描述：fd_material_depict
        储位号：fd_stock_number
        库存数量：fd_stock_count
        安全库存数量：fd_safe_stock_count */

        Map<String, List<MaterialFactoryEntity>> map = list4Map(materialFactoryEntities);
        for (String key : map.keySet()) {
            formValues = new JSONObject();
            //物料工厂id
            formValues.put("fd_stock_alert", key);
            for (MaterialFactoryEntity materialFactoryEntitie : map.get(key)) {
                formValuesdetail = new JSONObject();
                //物料号
                formValuesdetail.put("fd_stock_alert.fd_material_number", materialFactoryEntitie.getMaterialCode());
                //物料描述
                formValuesdetail.put("fd_stock_alert.fd_material_depict", materialFactoryEntitie.getMaterialDesc());
                //储位号
                formValuesdetail.put("fd_stock_alert.fd_stock_number", materialFactoryEntitie.getStorage());
                //库存数量
                formValuesdetail.put("fd_stock_alert.fd_stock_count", materialFactoryEntitie.getQunatity());
                //安全库存数量
                formValuesdetail.put("fd_stock_alert.fd_safe_stock_count", materialFactoryEntitie.getSafeCont());
                Map<String, Object> mapTypes = JSON.parseObject(formValuesdetail.toString());
                Lists.add(mapTypes);
            }
        }
        finalformValuesdetail = new JSONObject();
        String fd_stock_alert[] = new String[Lists.size()];
        String fd_material_number[] = new String[Lists.size()];
        String fd_material_depict[] = new String[Lists.size()];
        String fd_stock_number[] = new String[Lists.size()];
        String fd_stock_count[] = new String[Lists.size()];
        String fd_safe_stock_count[] = new String[Lists.size()];
        int index = 0;
        for (Map<String, Object> m : Lists) {
            for (String key : m.keySet()) {
                if ("fd_stock_alert".equals(key)) {
                    fd_stock_alert[index] = (String) m.get(key);
                }
                if ("fd_stock_alert.fd_material_number".equals(key)) {
                    fd_material_number[index] = (String) m.get(key);
                }
                if ("fd_stock_alert.fd_material_depict".equals(key)) {
                    fd_material_depict[index] = (String) m.get(key);
                }
                if ("fd_stock_alert.fd_stock_number".equals(key)) {
                    fd_stock_number[index] = m.get(key).toString();
                }
                if ("fd_stock_alert.fd_stock_count".equals(key)) {
                    fd_stock_count[index] = m.get(key).toString();
                }
                if ("fd_stock_alert.fd_safe_stock_count".equals(key)) {
                    fd_safe_stock_count[index] = (String) m.get(key);
                }
            }
            index++;
        }
        finalformValuesdetail.put("fd_stock_alert.fd_material_number", fd_material_number);
        finalformValuesdetail.put("fd_stock_alert.fd_material_depict", fd_material_depict);
        finalformValuesdetail.put("fd_stock_alert.fd_stock_number", fd_stock_number);
        finalformValuesdetail.put("fd_stock_alert.fd_stock_count", fd_stock_count);
        finalformValuesdetail.put("fd_stock_alert.fd_safe_stock_count", fd_safe_stock_count);
        //明细表的id
        formValues.put("fd_stock_alert", finalformValuesdetail);
        form.setFormValues(formValues.toJSONString());
        return form;
    }

    /**
     * @Description :数据同步oa
     * @Param [list]
     * @Return java.util.Map<java.lang.String, java.util.List < com.hs.srm.admin.modules.material.entity.MaterialFactoryEntity>>
     * @Author socik
     * @Date 2019/6/17 9:27
     */

    public Map<String, List<MaterialFactoryEntity>> list4Map(List<MaterialFactoryEntity> list) {
        Map<String, List<MaterialFactoryEntity>> map = new HashMap<String, List<MaterialFactoryEntity>>();
        if ((list != null) && (list.size() != 0)) {
            for (MaterialFactoryEntity materialFactoryEntity : list) {
                //物料工厂ID
                List<MaterialFactoryEntity> testList = map.get(materialFactoryEntity.getMaterialFactoryId());
                if (testList == null) {
                    testList = new ArrayList<MaterialFactoryEntity>();
                }
                testList.add(materialFactoryEntity);
                map.put(materialFactoryEntity.getMaterialFactoryId(), testList);
            }
        }
        return map;
    }
}
